import { useEffect, useRef } from "react"
import { echarts } from "@/config/echartsConfig"
import { debounce } from "lodash"

function useECharts() {
  const chartRef = useRef(null)
  const chartInstanceRef = useRef(null)

  useEffect(() => {
    if (chartRef.current) {
      // 初始化 ECharts 实例
      chartInstanceRef.current = echarts.init(chartRef.current)

      // 定义防抖函数
      const resizeChart = debounce(() => {
        chartInstanceRef.current.resize()
      }, 200)

      // 监听窗口大小变化
      window.addEventListener("resize", resizeChart)

      // 清理函数
      return () => {
        window.removeEventListener("resize", resizeChart)
        resizeChart.cancel()
        if (chartInstanceRef.current) {
          chartInstanceRef.current.dispose()
          chartInstanceRef.current = null
        }
      }
    }
  }, [])

  return chartRef
}

export default useECharts
